<template>
  <div class="search-date">
    <slot name="title"
      ><div class="date-title">
        {{ $t('common.tips.select_date') }}
      </div></slot
    >
    <div class="date-content">
      <div class="date-start">
        <div class="tip-title">
          {{ $t('common.global.start_date') }}
        </div>
        <el-date-picker
          v-model="start"
          clearable
          value-format="X"
          type="date"
          :disabled-date="startDisabledDateFn"
          :placeholder="$t('common.placeholder.select_date')"
        />
      </div>
      <div class="date-end">
        <div class="tip-title">
          {{ $t('common.global.end_date') }}
        </div>
        <el-date-picker
          clearable
          type="date"
          value-format="X"
          :model-value="end"
          :disabled-date="endDisabledDateFn"
          :placeholder="$t('common.placeholder.select_date')"
          @update:model-value="onUpdateEnd"
        />
      </div>
    </div>
    <div class="search-popover-footer">
      <el-button size="small" @click="handleCancel">{{
        $t('common.global.cancel')
      }}</el-button>
      <el-button
        type="primary"
        size="small"
        :disabled="!start && !end"
        @click="handleOk"
        >{{ $t('common.global.confirm') }}</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { dayjs, ElButton, ElDatePicker } from 'element-plus'
import { ref } from 'vue'

const props = defineProps<{
  startDisabledDate?: Function
  endDisabledDate?: Function
}>()

const emit = defineEmits<{
  ok: [value: number[]]
  cancel: []
}>()

const start = ref()
const end = ref()

function onClear() {
  start.value = undefined
  end.value = undefined
}

function handleCancel() {
  emit('cancel')
  onClear()
}

function startDisabledDateFn(value: Date) {
  if (end.value) {
    const endDate = dayjs.unix(end.value)
    const startDate = dayjs(value)
    return (
      !startDate.isBefore(endDate.add(1, 'day')) ||
      props.startDisabledDate?.(value)
    )
  }
  return props.startDisabledDate?.(value)
}

function endDisabledDateFn(value: Date) {
  if (start.value) {
    const startDate = dayjs.unix(start.value)
    const endDate = dayjs(value)
    return (
      !endDate.isAfter(startDate.subtract(1, 'day')) ||
      props.endDisabledDate?.(value)
    )
  }
  return props.endDisabledDate?.(value)
}

function onUpdateEnd(val: string) {
  end.value = !val ? val : String(+val + 86399)
}

function handleOk() {
  emit('ok', [start.value, end.value])
  onClear()
}
</script>
